<?php

namespace App\Controller\Home;

use App\Models\Conn;
use Core\Result\Result;
use Core\Utils\Utils;

class Wechat
{
    private $app_id = 'wx3a141acec303c5fe';
    private $app_secret = '683f2751468a44df060354200fe4a666';
    private $scope = 'snsapi_userinfo';

    /**
     * 获取微信openid
     *
     * @return mixed|string
     */
    public function getAuthorizeUrl($data)
    {
        $code = $data["code"];
        $token = $data["token"];
        if(empty($code)){
            $redirect_uri = "http://demo.cmhm.xyz/web";
            $redirect_uri = urlencode($redirect_uri);
            $state = Utils::alnum();
            $url= "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope={$this->scope}&state={$state}#wechat_redirect";
            Result::success($url);
        }
        $accessToken = $this->getAccessToken($code);
        if(!empty($accessToken["openid"])){
            $conn = new Conn();
            $sql="UPDATE `users` SET `openid` = '$accessToken[openid]' WHERE `token` = '$token'";
            $conn->executeConn($sql);
        }
        Result::success($accessToken);
    }
    public function getSignPackage($url){
        $jsapiTicket = $this->getJsApiTicket();
        // 注意 URL 一定要动态获取，不能 hardcode.
        //$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        //$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        Result::success($signPackage);
    }
    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        $data = json_decode($this->get_php_file("jsapi_ticket.php"));
        if ($data->expire_time < time()) {
            $accessToken = $this->getAccessToken();
            // 如果是企业号用以下 URL 获取 ticket
            // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $this->set_php_file("jsapi_ticket.php", json_encode($data));
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }

        return $ticket;
    }
    /**
     * @author: zxf
     * @date: 2018-12-08
     * @description: 解密微信用户敏感数据
     * @return array
     */
    public function wxDecode($data)
    {
        $appid = $this->app_id;
        $appsecret = $this->app_secret;
        $grant_type = "authorization_code"; //授权（必填）
        $code = $data['code']; //有效期5分钟 登录会话
        $encryptedData=$data['encryptedData'];
        $iv = $data['iv'];
        $signature = $data['signature'];
        $rawData = $data['rawData'];
        // 拼接url
        $url = "https://api.weixin.qq.com/sns/jscode2session?"."appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=".$grant_type;
        $res = json_decode($this->httpGet($url),true);
        return $res;
        //$sessionKey = $res['session_key']; //取出json里对应的值
        //$openid = $res['openid']; //openid

        /*$signature2 = sha1(htmlspecialchars_decode($rawData).$sessionKey);
        // 验证签名
        if ($signature2 !== $signature){
            return json("验签失败");
        }*/
        // 获取解密后的数据
        /*$pc = new WxBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            Result::success($data);
        } else {
            Result::error($errCode);
        }*/
    }
    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData( $encryptedData, $iv, &$data )
    {
        if (strlen($this->sessionKey) != 24) {
            return ErrorCode::$IllegalAesKey;
        }
        $aesKey=base64_decode($this->sessionKey);


        if (strlen($iv) != 24) {
            return ErrorCode::$IllegalIv;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return ErrorCode::$IllegalBuffer;
        }
        if( $dataObj->watermark->appid != $this->appid )
        {
            return ErrorCode::$IllegalBuffer;
        }
        $data = $result;
        return ErrorCode::$OK;
    }
    /**
     * 获取授权token网页授权
     *
     * @param string $code
     * @return mixed|string
     */
    public function getAccessToken($code = '')
    {
        $params = [
            'appid'      => $this->app_id,
            'secret'     => $this->app_secret,
            'code'       => $code,
            'grant_type' => 'authorization_code'
        ];
        $utils = new Utils();
        $sendCurl = $utils->sendCurl("https://api.weixin.qq.com/sns/oauth2/access_token", $params);
        //$ret = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token', $params, 'GET');
        if ($sendCurl) {
            $ar = json_decode($sendCurl, true);
            return $ar;
        }
        return [];
    }
    public function getJsticket($code = '')
    {
        $token = $this->getAccessToken($code);
        $params = [
            'access_token' => 'token',
            'type'         => 'jsapi',
        ];
        //$ret = Http::sendRequest('https://api.weixin.qq.com/cgi-bin/ticket/getticket', $params, 'GET');
        $utils = new Utils();
        $ret = $utils->sendCurl("https://api.weixin.qq.com/sns/oauth2/access_token", $params);
        if ($ret['ret']) {
            $ar = json_decode($ret['msg'], true);
            return $ar;
        }
    }
    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);

        $res = curl_exec($curl);
        curl_close($curl);

        return $res;
    }
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    private function get_php_file($filename) {
        return trim(substr(file_get_contents($filename), 15));
    }
    private function set_php_file($filename, $content) {
        $fp = fopen($filename, "w");
        fwrite($fp, "<?php exit();?>" . $content);
        fclose($fp);
    }
}